<?php
/*
  功能：平台用户 model
  作者：cxm
  时间：2019-01-11
*/

namespace App\Models;

use App\Models\News\Notification;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;

class AdminUser extends BaseModel {
    use Notifiable;
    use SoftDeletes;
    protected $dates = ['deleted_at']; //开启deleted_at
    protected $table='admin_user';  //绑定表

    protected $hidden = ['password','remember_token'];

    /**
     * 获取用户消息列表
     */
    public function notifications ()
    {
        return $this->hasMany(Notification::class, 'notifiable_id', 'id')
            ->where('type','App\Notifications\SystemNotification')
            ->orderBy('created_at', 'desc');
    }

    /**
     * 获取用户已读消息
     */
    public function unreadNotifications ()
    {
        return $this->hasMany(Notification::class, 'notifiable_id', 'id')->orderBy('created_at', 'desc')
            ->where('type','App\Notifications\SystemNotification')
            ->whereNotNull('read_at');
    }

    /**
     * 获取用户未读读消息
     */
    public function readNotifications ()
    {
        return $this->hasMany(Notification::class, 'notifiable_id', 'id')->orderBy('created_at', 'desc')
            ->where('type','App\Notifications\SystemNotification')
            ->whereNull('read_at');
    }
    /**
     * 头像
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function file(){
        return $this->hasOne(File::class,'id','avatar');
    }

    /**
     * 用户权限
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function user_role(){
        return $this->hasOne(AdminUserRole::class,'user_id','id');
    }

    /**
     * 获取管理员列表
     * @param $params 搜索参数
     * @return mixed
     */
    public static function getData($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : config('exam.pageSize');
        $result = self::orderBy('created_at','desc')
            ->with([
                'user_role'=>function($query){ // 管理员权限
                    $query->select('id','role_id','user_id')->with('role');
                }
                ,'file' =>function ($query) { // 头像
                    $query->select('id','path');
                }
            ]);
        // 账号
        if (!empty($params['username'])) {
            $result->where('username','like','%'.$params['username'].'%');
        }
        // 名称
        if (!empty($params['name'])) {
            $result->where('name','like','%'.$params['name'].'%');
        }

        // 角色
        if (!empty($params['role_id'])) {
            $role_id = $params['role_id'];
            $result->whereHas('user_role',function($query)use($role_id){
                $query->where('role_id',$role_id);
            });
        }
        $total = $result->count();
        $data = $result->skip(($page-1)*$limit)->take($limit)->get()->toArray();
        return ['total'=>$total,'data'=>$data];
    }

    /**
     * 编辑
     * @param array $where
     * @param array $field
     * @return mixed
     */
    public static function updated($where=array(),$field=array()){
        return self::where($where)->update($field);
    }

    /**
     * 编辑
     * @param array $where
     * @param array $field
     * @return mixed
     */
    public static function modify($where=array(),$field=array()){
        return self::where($where)->update($field);
    }

    /**
     * 查看是否有超级管理员
     * @param $ids
     * @return mixed
     */
    public static function isSuperMan($ids){
        $user_type = self::whereIn('id',$ids)->pluck('user_type')->toArray();
        if (in_array(1,$user_type)) {
            return true;
        }
        return false;
    }

    /**
     * 获取用户权限
     * sql执行时间0.0058s
     * @param $user_id
     * @return mixed
     */
    public static function getUserPermission($user_id){
        return self::join('admin_user_role as user_role', 'admin_user.id', '=', 'user_role.user_id')
            ->join('admin_role as role', 'user_role.role_id', '=', 'role.id')
            ->join('admin_role_permission as role_permission', 'role.id', '=', 'role_permission.role_id')
            ->join('admin_permission as permission', 'role_permission.permission_id', '=', 'permission.id')
            ->where('admin_user.id', '=', $user_id)
            ->groupBy('permission.id')
            ->orderBy('permission.pid', 'desc')
            ->select(
                'permission.id'
                , 'permission.pid'
                , 'permission.name'
                , 'permission.http_path as path'
                , 'permission.http_method as method'
                , 'permission.icon'
                , 'permission.sort'
            )
            ->get()
            ->toArray();
    }

    /**
     * 设置密码
     * @param $data
     * @return mixed
     * @throws
     */
    public static function setPass($data)
    {
        DB::beginTransaction();
        try {
            $re = self::where('id', $data['id'])->update(['password' => $data['password']]);
            if ($re === false) {
                throw new \Exception('重置失败！');
            }
            DB::commit();
            return ['code' => 0, 'msg' => ''];
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['code' => 1, 'msg' => $exception];
        }
    }

    /**
     * 禁用、启用
     * @param $data
     * @return mixed
     * @throws
     */
    public static function set($data)
    {
        DB::beginTransaction();
        try {
            if (is_array($data['id'])) {
                $mode = self::whereIn('id', $data['id']);
            } else {
                $mode = self::where('id', $data['id']);
            }
            $re = $mode->update(['status' => $data['status']]);
            if ($re === false) {
                throw new \Exception('设置失败！');
            }
            DB::commit();
            return ['code' => 0, 'msg' => ''];
        } catch (\Exception $exception) {
            DB::rollBack();
            return ['code' => 1, 'msg' => $exception];
        }
    }
}